let requestUrl;
let form = new FormData();

/**
 * 添加
 */
function addHandler() {
	requestUrl = "/role_account/insert";

	$("#id").textbox("readonly", false);

	$("#role_dialog").dialog("open");
}

/**
 * 修改
 */
function editHandler() {
	let rowData = $("#role_list").datagrid("getSelected");
	
	if (rowData) {
		requestUrl = "/role_account/updateById";

		$("#id").textbox("readonly", true);
		$('#id').textbox("setValue", rowData.id);

		$("#name").textbox("setValue", rowData.name);
		$("#jinbi").numberspinner("setValue", rowData.jinbi);
		$("#gangId").combobox("setValue", rowData.gangId);
		$("#grade").numberspinner("setValue", rowData.grade);
		$("#score").numberspinner("setValue", rowData.score);
		$("#schoolId").combobox("setValue", rowData.schoolId);
		$("#serverId").combobox("setValue", rowData.serverId);
		$("#birthday").datetimebox("setValue", rowData.birthday);
		$("#accountId").combobox("setValue", rowData.accountId);
		$("#modelingId").combobox("setValue", rowData.modelingId);

		$("#role_dialog").dialog("open");
	} else {
		alertMsg("请选择要修改的记录！", "warning");
	}
}

/**
 * 删除
 */
function deleteHandler() {
	let rowData = $("#role_list").datagrid("getSelected");

	if (rowData) {
		$.messager.confirm("提示", "是否确认删除？", function(bool) {
			if (bool) {
				ajaxPost("/role_account/deleteById", {
					id: rowData.id
				}, function(response) {
					showMsg(response.message);

					$("#role_list").datagrid("reload");
				}, error);
			}
		});
	} else {
		alertMsg("请选择要删除的数据~", "warning");
	}
}

$(document).ready(function() {

	$("#id").textbox({
		width: 120,
		required: true
	});
	
	$("#name").textbox({
		width: 120,
		required: true
	});

	$("#grade").numberspinner({
        min: 0,
        max: 115,
        width: 120,
        editable: true,
        required: true
    });

	$("#schoolId").combobox({
        url: "/school/selectAll",
        valueField: "id",
		textField: "name",
		width: 120,
		required: true,
		formatter: function(row) {
			return "<img alt='' height='20' src='" + row.image + "' />&nbsp;" + row.name;
		},
		onSelect: function(record){
			if(record) {
				let url = "/role_modeling/selectByPhyle";

				url += "?phyle=" + record.phyle;

				if (record.gender) {
					url += "&gender=" + record.gender;
				}

				$("#modelingId").combobox("reload", url);
			}
	    }
	});
	
	$("#modelingId").combobox({
        url: "/role_modeling/selectByPhyle",
        valueField: "id",
		textField: "name",
		width: 120,
		editable: true,
		required: true,
		groupField: "phyle",
		groupFormatter: function(group) {
			ajaxGet("/phyle/selectById", {
				id: group
			}, function (resp) {
				let data = resp.data;

				$("#_phyle_" + group).html(data.name);
			}, error);

			return "<span class='blue' id='_phyle_" + group + "'></span>";
		},
		formatter: function(row) {
			return "<img alt='' width='20' src='" + row.image + "' />&nbsp;" + row.name;
		}
    });

	$("#gangId").combobox({
		url: "/gang/selectAll",
		valueField: "id",
		textField: "name",
		width: 120
	});

	$("#score").numberspinner({
        min: 0,
        width: 120,
        required: true
    });

	$("#jinbi").numberspinner({
		min: 0,
		max: 9999999999,
		width: 120,
		required: true
	});
	
    $("#area_id").combobox({
        url: "/area/selectAll",
        valueField: "id",
		textField: "name",
		width: 120,
		prompt: "--大区--",
	    onSelect: function(record){
	        if(record) {
				let url = "/server/selectByAreaId?areaId=" + record.id;

	        	$("#serverId").combobox("reload", url);
	        }
	    }
    });
    
    $("#serverId").combobox({
        url: "/server/selectAll",
        valueField: "id",
		textField: "name",
		width: 125,
		required: true,
		prompt: "--服务器--"
	});

    $("#accountId").combobox({
        url: "/account/selectAll",
        valueField: "id",
		textField: "account",
		width: 250,
		required: true
    });

	$("#birthday").datetimebox({
		width: 176,
		required: true,
		showSeconds: true
	});
    
	$("#role_dialog").dialog({
		title: "角色信息",
		buttons: [{
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				let selector = "#role_form";

				checkForm(selector, function () {
					let data = $(selector).serialize();

					ajaxPost(requestUrl, data, function(response) {
						showMsg(response.message);

						$(selector).form("clear");
						// 关闭对话框
						$("#role_dialog").dialog("close");
						// 刷新角色列表
						$("#role_list").datagrid("reload");

						// 重新加载门派和角色造型下拉框的数据
						$("#schoolId").combobox("reload", "/school/selectAll");
						$("#modelingId").combobox("reload", "/role_modeling/selectAll");
					}, error);
				});
			}
		}, {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				$("#role_form").form("clear");
				$("#role_dialog").dialog("close");

				$("#schoolId").combobox("reload", "/school/selectAll");
				$("#modelingId").combobox("reload", "/role_modeling/selectAll");
			}
		}]
	});

	let datagrid = $("#role_list").datagrid({
		url: "/role_account/selectByPage",
		title: "角色列表",
		height: table_height_with_search,
		rownumbers: true,
		pagination: true,
		remoteFilter: true,
		clientPaging: false,
		onHeaderContextMenu: function(e) {
			e.preventDefault();

			if (!columnMenu){
				createColumnMenu("#role_list");
			}
			columnMenu.menu("show", {
				left: e.pageX,
				top: e.pageY
			});
		},
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				addHandler();
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				editHandler();
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				deleteHandler();
			}
		}],
		columns: [[
			{field: "id", title: "角色ID", align: "center", sortable: true, width: 150},
			{field: "name", title: "角色名", align: "center", width: 150},
			{field: "modelingId", title: "角色造型", align: "center", width: 150
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/role_modeling/selectById", {
						id: value
					}, function(res) {
						let result = res.data;

						$("#modeling_" + rowIndex).attr("src", result.image)
							.attr("title", result.name);
					}, error);
					
					return "<img alt='' height='" + size + "' id='modeling_" + rowIndex + "' />";
				}
			},
			{field: "grade", title: "等级", align: "center", sortable: true, width: 120
				, formatter: function(value) {
					let group; // 组别
					
					if(value >= 0 && value <= 69) { // [0, 69]精锐组
						group = "精锐组";
					} else if(value >= 70 && value <= 89) { // [70, 89]勇武组
						group = "勇武组";
					} else if(value >= 90) { // [90, 115]神威组
						group = "神威组";
					} else { // [-∞, 0) ∪ (115, +∞)
						group = "等级不合法";
					}
					
					return "<span title='" + group + "'>" + value+ "级</span>";
				}
			},
			{field: "score", title: "人物评分", align: "center", sortable: true, width: 120},
			{field: "schoolId", title: "门派", align: "center", width: 150
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/school/selectById", {
						id: value
					}, function(res) {
						let result = res.data;

						$("#school_" + rowIndex).attr("src", result.image)
							.attr("title", result.name);
					}, error);
					
					return "<img alt='' height='" + size + "' id='school_" + rowIndex + "' />";
				}
			},
			{field: "jinbi", title: "金币", align: "center", sortable: true, width: 120},
			{field: "serverId", title: "服务器", align: "center", width: 120
				, formatter: function(value, rowData, rowIndex) {
					if (value) {
						ajaxGet("/server/selectById", {
							id: value
						}, function (resp) {
							let data = resp.data;

							ajaxGet("/area/selectById", {
								id: data.areaId
							}, function (response) {
								let result = response.data;

								$("#server_" + rowIndex).html(result.name + "-" + data.name);
							}, error);
						}, error);

						return "<div id='server_" + rowIndex + "'></div>";
					} else {
						return "<div>/</div>";
					}
				}
			},
			{field: "accountId", title: "账号", align: "center", width: 200
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/account/selectById", {
						id: value
					}, function(res) {
						$("#account_" + rowIndex).html(res.data.account);
					}, error);

					return "<div id='account_" + rowIndex + "'></div>";
				}
			},
			{field: "lastUpdateTime", title: "最后一次修改时间", align: "center", sortable: true, width: 200, hidden: true}
		]]
	});

	datagrid.datagrid("enableFilter", [{
		field: "id",
		type: "textbox",
		op: ["equal"]
	}, {
		field: "name",
		type: "textbox",
		op: ["equal", "contains"]
	}, {
		field: "grade",
		type: "numberspinner",
		op: ["equal", "less", "lessorequal", "greater", "greaterorequal"],
		options: {
			min: 1,
			max: 115
		}
	}, {
		field: "score",
		type: "numberspinner",
		op: ["equal", "less", "lessorequal", "greater", "greaterorequal"],
		options: {
			min: 0
		}
	}, {
		field: "jinbi",
		type: "numberspinner",
		op: ["equal", "less", "lessorequal", "greater", "greaterorequal"],
		options: {
			min: 0
		}
	}, {
		field: "schoolId",
		type: "combobox",
		options: {
			url: "/school/selectAll",
			valueField: "id",
			textField: "name",
			panelHeight: "auto",
			formatter: function(row) {
				return "<img alt='' width='20' src='" + row.image + "' />&nbsp;" + row.name;
			}
		},
		op: ["equal"]
	}, {
		field: "modelingId",
		type: "combobox",
		options: {
			url: "/role_modeling/selectAll",
			valueField: "id",
			textField: "name",
			panelHeight: "auto",
			groupField: "phyle",
			groupFormatter: function(group) {
				ajaxGet("/phyle/selectById", {
					id: group
				}, function (res) {
					$("#phyle_" + group).html(res.data.name);
				}, error);

				return "<span class='red' id='phyle_" + group + "'></span>";
			},
			formatter: function(row) {
				return "<img alt='' width='20' src='" + row.image + "' />&nbsp;" + row.name;
			}
		},
		op: ["equal"]
	}, {
		field: "accountId",
		type: "combobox",
		options: {
			url: "/account/selectAll",
			valueField: "id",
			textField: "account",
			panelHeight: "auto",
		},
		op: ["equal"]
	}]);

});